package com.weigecoder.warehouse.task;

import com.weigecoder.warehouse.constant.WarehouseConstants;
import com.weigecoder.warehouse.utils.QiniuUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 定时任务的执行,定时清理垃圾图片
 */
@Slf4j
@Component
public class JobTask {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private QiniuUploadUtil qiniuUploadUtil;

    //cron表达式
    //每两秒执行一次
    //@Scheduled(cron = "0/2 * * * * ?")
    //从六月开始，每个月执行一次
    //@Scheduled(cron = "* * * * 6/1 ? ")

    //表示每天凌晨0点执行一次定时任务
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearImg() {
        //找差集，然后删除差集中的图片
        Set<String> diff = redisTemplate.boundSetOps(WarehouseConstants.PRODUCT_IMAGES_RESOURCES).diff(WarehouseConstants.PRODUCT_IMAGES_DB_RESOURCES);
        if (diff != null) {
            for (String fileName : diff) {
                log.info("定时清理垃圾图片:{}", fileName);
                //根据图片名称从七牛云服务器删除文件
                qiniuUploadUtil.deleteFileFromQiniu(fileName);
                //从redis集合中删除图片名称
                redisTemplate.boundSetOps(WarehouseConstants.PRODUCT_IMAGES_RESOURCES).remove(fileName);
            }
        }
    }
}
